import Vue from "vue";
import Router from "vue-router";
import store from "@/store/index";
import NProgress from "nprogress";
import { getAdminToken, removeAdminToken } from "@/utils/auth";
// NProgress 进度条样式, 可自行找到该文件进行编辑样式
import "nprogress/nprogress.css";
import { Message, Notification } from "element-ui";

// 解决重定向到当前路由发生报错
const routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => {
    console.log(error);
  });
};

Vue.use(Router);


// 不需要角色权限的路径
var publicUrl = [
  "/",
  "/err_404",
  "/login",
  "/manage",
  "/manage/welcome"
];

var router = new Router({
  mode: "history",
  base: "/admin/",
  // 公共路径
  routes: [
    {
      path: "/",
      component: () => import("@/views/Login"),
      meta: {
        title: "登录"
      }
    },
    {
      path: "/login",
      component: () => import("@/views/Login"),
      meta: {
        title: "登录"
      }
    },
    {
      path: "/index.vue",
      component: () => import("@/views/Manage"),
      meta: {
        title: "首页",
        requireAuth: true
      },
      children: []
    },
    {
      path: "/err_404",
      component: () => import("@/views/error/404"),
      meta: {
        title: "找不到页面"
      }
    }
    // {
    // 	// 通配符, 匹配所有路径, 没有匹配相应的路径时会进入到这里
    // 	path: '*',
    // 	component: ()=> import('@/views/error/404'),
    // }
  ]
});

// 页面加载进度样式配置
NProgress.configure({
  easing: "ease", // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: false, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3 // 初始化时的最小百分比
});


router.beforeEach((to, form, next) => {
  // 每次切换页面时，调用进度条
  NProgress.start();
  let token = getAdminToken();
  if (token) {
    // 路由变化修改title
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    // 有token 直接跳转到管理界面
    if (to.path === "/login" || to.path === "/") {
      next({ path: "/index.vue" });
    }else{
      if (isNeedAdInfoRefresh()) {
        store.dispatch("GetInfo").then(() => {
          next({ ...to, replace: true });
        }).catch(err => {
          console.log(err);
          store.dispatch("LogOut").then(r => {
            Message.error(err);
            next({
              path: "/login",
              query: {
                redirect: to.fullPath
              } // 将跳转的路由path作为参数，登录成功后跳转到该路由
            });
          });
        });
      } else {
        next();
      }
    }

  } else {
    // 没有token 并 不在白名单
    if (publicUrl.indexOf(to.path) === -1) {
      const redirect = encodeURIComponent(to.fullPath); // 编码 URI，保证参数跳转回去后，可以继续带上
      next(`/login?redirect=${redirect}`); // 否则全部重定向到登录页
      NProgress.done();
    } else {
      next();
    }
  }
});

router.afterEach((to, form) => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done();
});

function isNeedAdInfoRefresh() {
  let user = store.getters.user;
  return user.roles.length === 0 || user.permissions.length === 0 || user.routeList.length === 0;
}

export default router;
